import React, { useState } from 'react';
import { getAllMissions, getMissionTypes } from '../utils/MissionScenarios';
import './UnifiedControlPanel.css';

const UnifiedControlPanel = ({
  // ControlPanel props
  animationSpeed,
  setAnimationSpeed,
  showComponents,
  setShowComponents,
  colors,
  setColors,
  showGrid,
  setShowGrid,
  showStats,
  setShowStats,
  onExport,
  showTrails,
  setShowTrails,

  // TelemetryDisplay props
  flightState,

  // MissionControl props
  flightController,
  onMissionStart,
  onMissionStop,

  // FormationControl props
  formationController,
  formationState,

  // Environment props
  showObstacles,
  setShowObstacles,
  showBoundaries,
  setShowBoundaries,
  showTerrain,
  setShowTerrain,
  mapSize,
  setMapSize,

  // Camera props
  cameraSettings,
  setCameraSettings,
}) => {
  const [activeTab, setActiveTab] = useState('controls');
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [expandedSections, setExpandedSections] = useState({});

  const tabs = [
    { id: 'controls', label: '🎛️ Controls', icon: '🎛️' },
    { id: 'telemetry', label: '📊 Telemetry', icon: '📊' },
    { id: 'mission', label: '🎯 Mission', icon: '🎯' },
    { id: 'formation', label: '🔗 Formation', icon: '🔗' },
    { id: 'environment', label: '🌍 Environment', icon: '🌍' },
    { id: 'camera', label: '🎥 Camera', icon: '🎥' },
    { id: 'keyboard', label: '⌨️ Keyboard', icon: '⌨️' }
  ];

  const toggleSection = (section) => {
    setExpandedSections(prev => ({
      ...prev,
      [section]: !prev[section]
    }));
  };

  const handleComponentToggle = (component) => {
    setShowComponents(prev => ({
      ...prev,
      [component]: !prev[component]
    }));
  };

  const handleColorChange = (component, color) => {
    setColors(prev => ({
      ...prev,
      [component]: color
    }));
  };

  return (
    <div className={`unified-control-panel ${isCollapsed ? 'collapsed' : ''}`}>
      {/* Header with tabs */}
      <div className="control-header">
        <div className="tab-navigation">
          {tabs.map(tab => (
            <button
              key={tab.id}
              className={`tab-button ${activeTab === tab.id ? 'active' : ''}`}
              onClick={() => setActiveTab(tab.id)}
            >
              <span className="tab-icon">{tab.icon}</span>
              <span className="tab-label">{tab.label}</span>
            </button>
          ))}
        </div>
        <button
          className="collapse-button"
          onClick={() => setIsCollapsed(!isCollapsed)}
        >
          {isCollapsed ? '▼' : '▲'}
        </button>
      </div>

      {/* Content area */}
      {!isCollapsed && (
        <div className="control-content">
          {activeTab === 'controls' && (
            <ControlsTab
              animationSpeed={animationSpeed}
              setAnimationSpeed={setAnimationSpeed}
              showComponents={showComponents}
              handleComponentToggle={handleComponentToggle}
              colors={colors}
              handleColorChange={handleColorChange}
              showGrid={showGrid}
              setShowGrid={setShowGrid}
              showStats={showStats}
              setShowStats={setShowStats}
              onExport={onExport}
              showTrails={showTrails}
              setShowTrails={setShowTrails}
              expandedSections={expandedSections}
              toggleSection={toggleSection}
            />
          )}

          {activeTab === 'telemetry' && (
            <TelemetryTab flightState={flightState} />
          )}

          {activeTab === 'mission' && (
            <MissionTab
              flightController={flightController}
              onMissionStart={onMissionStart}
              onMissionStop={onMissionStop}
              flightState={flightState}
            />
          )}

          {activeTab === 'formation' && (
            <FormationTab
              formationController={formationController}
              formationState={formationState}
            />
          )}

          {activeTab === 'environment' && (
            <EnvironmentTab
              showObstacles={showObstacles}
              setShowObstacles={setShowObstacles}
              showBoundaries={showBoundaries}
              setShowBoundaries={setShowBoundaries}
              showTerrain={showTerrain}
              setShowTerrain={setShowTerrain}
              mapSize={mapSize}
              setMapSize={setMapSize}
            />
          )}

          {activeTab === 'camera' && (
            <CameraTab
              cameraSettings={cameraSettings}
              setCameraSettings={setCameraSettings}
            />
          )}

          {activeTab === 'keyboard' && (
            <KeyboardTab flightState={flightState} />
          )}
        </div>
      )}
    </div>
  );
};

// Controls Tab Component
const ControlsTab = ({
  animationSpeed,
  setAnimationSpeed,
  showComponents,
  handleComponentToggle,
  colors,
  handleColorChange,
  showGrid,
  setShowGrid,
  showStats,
  setShowStats,
  onExport,
  showTrails,
  setShowTrails,
  expandedSections,
  toggleSection
}) => {
  return (
    <div className="tab-content controls-tab">
      <div className="content-grid">

        {/* Animation Controls */}
        <div className="control-section">
          <div
            className="section-header"
            onClick={() => toggleSection('animation')}
          >
            <h3>⚡ Animation</h3>
            <span className={`dropdown-arrow ${expandedSections.animation ? 'expanded' : ''}`}>▼</span>
          </div>
          {expandedSections.animation && (
            <div className="section-content">
              <div className="control-item">
                <label>Speed: {animationSpeed.toFixed(1)}x</label>
                <input
                  type="range"
                  min="0.1"
                  max="3"
                  step="0.1"
                  value={animationSpeed}
                  onChange={(e) => setAnimationSpeed(parseFloat(e.target.value))}
                />
              </div>
            </div>
          )}
        </div>

        {/* Component Visibility */}
        <div className="control-section">
          <div
            className="section-header"
            onClick={() => toggleSection('components')}
          >
            <h3>🔧 Components</h3>
            <span className={`dropdown-arrow ${expandedSections.components ? 'expanded' : ''}`}>▼</span>
          </div>
          {expandedSections.components && (
            <div className="section-content">
              {Object.entries(showComponents).map(([component, visible]) => (
                <div key={component} className="control-item">
                  <label>
                    <input
                      type="checkbox"
                      checked={visible}
                      onChange={() => handleComponentToggle(component)}
                    />
                    {component.charAt(0).toUpperCase() + component.slice(1)}
                  </label>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Color Controls */}
        <div className="control-section">
          <div
            className="section-header"
            onClick={() => toggleSection('colors')}
          >
            <h3>🎨 Colors</h3>
            <span className={`dropdown-arrow ${expandedSections.colors ? 'expanded' : ''}`}>▼</span>
          </div>
          {expandedSections.colors && (
            <div className="section-content">
              {Object.entries(colors).map(([component, color]) => (
                <div key={component} className="control-item">
                  <label>{component.charAt(0).toUpperCase() + component.slice(1)}:</label>
                  <input
                    type="color"
                    value={color}
                    onChange={(e) => handleColorChange(component, e.target.value)}
                  />
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Display Options */}
        <div className="control-section">
          <div
            className="section-header"
            onClick={() => toggleSection('display')}
          >
            <h3>👁️ Display</h3>
            <span className={`dropdown-arrow ${expandedSections.display ? 'expanded' : ''}`}>▼</span>
          </div>
          {expandedSections.display && (
            <div className="section-content">
              <div className="control-item">
                <label>
                  <input
                    type="checkbox"
                    checked={showGrid}
                    onChange={(e) => setShowGrid(e.target.checked)}
                  />
                  Show Grid
                </label>
              </div>
              <div className="control-item">
                <label>
                  <input
                    type="checkbox"
                    checked={showStats}
                    onChange={(e) => setShowStats(e.target.checked)}
                  />
                  Performance Stats
                </label>
              </div>
              <div className="control-item">
                <label>
                  <input
                    type="checkbox"
                    checked={showTrails}
                    onChange={(e) => setShowTrails(e.target.checked)}
                  />
                  Flight Trails
                </label>
              </div>
            </div>
          )}
        </div>

        {/* Export Options */}
        <div className="control-section">
          <div
            className="section-header"
            onClick={() => toggleSection('export')}
          >
            <h3>📤 Export</h3>
            <span className={`dropdown-arrow ${expandedSections.export ? 'expanded' : ''}`}>▼</span>
          </div>
          {expandedSections.export && (
            <div className="section-content">
              <div className="export-buttons">
                <button onClick={() => onExport('screenshot')}>
                  📸 Screenshot
                </button>
                <button onClick={() => onExport('gltf')}>
                  📦 GLTF Model
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// Telemetry Tab Component
const TelemetryTab = ({ flightState }) => {
  if (!flightState) return <div className="tab-content">No telemetry data available</div>;

  const { telemetry, isFlying, autopilot, currentMission, missionProgress } = flightState;

  const formatValue = (value, decimals = 1) => {
    return typeof value === 'number' ? value.toFixed(decimals) : value;
  };

  const getStatusColor = (value, thresholds) => {
    if (value >= thresholds.good) return '#4CAF50';
    if (value >= thresholds.warning) return '#FF9800';
    return '#F44336';
  };

  const batteryColor = getStatusColor(telemetry.battery, { good: 50, warning: 20 });
  const signalColor = getStatusColor(telemetry.gpsSignal, { good: 80, warning: 50 });

  return (
    <div className="tab-content telemetry-tab">
      <div className="telemetry-grid">

        {/* Flight Status */}
        <div className="telemetry-section">
          <h4>Flight Status</h4>
          <div className="status-indicators">
            <div className={`status-indicator ${isFlying ? 'flying' : 'grounded'}`}>
              {isFlying ? '✈️ FLYING' : '🛬 GROUNDED'}
            </div>
            <div className={`status-indicator ${autopilot ? 'auto' : 'manual'}`}>
              {autopilot ? '🤖 AUTO' : '👨‍✈️ MANUAL'}
            </div>
          </div>
        </div>

        {/* Primary Flight Data */}
        <div className="telemetry-section">
          <h4>Flight Data</h4>
          <div className="data-grid">
            <div className="data-item">
              <span className="label">Altitude:</span>
              <span className="value">{formatValue(telemetry.altitude)} m</span>
            </div>
            <div className="data-item">
              <span className="label">Speed:</span>
              <span className="value">{formatValue(telemetry.speed)} m/s</span>
            </div>
            <div className="data-item">
              <span className="label">Heading:</span>
              <span className="value">{formatValue(telemetry.heading, 0)}°</span>
            </div>
            <div className="data-item">
              <span className="label">Pitch:</span>
              <span className="value">{formatValue(telemetry.pitch)}°</span>
            </div>
            <div className="data-item">
              <span className="label">Roll:</span>
              <span className="value">{formatValue(telemetry.roll)}°</span>
            </div>
            <div className="data-item">
              <span className="label">Yaw:</span>
              <span className="value">{formatValue(telemetry.yaw)}°</span>
            </div>
          </div>
        </div>

        {/* System Status */}
        <div className="telemetry-section">
          <h4>System Status</h4>
          <div className="status-bars">
            <div className="status-bar">
              <span className="status-label">Battery:</span>
              <div className="progress-bar">
                <div
                  className="progress-fill"
                  style={{
                    width: `${telemetry.battery}%`,
                    backgroundColor: batteryColor
                  }}
                />
              </div>
              <span className="status-value" style={{ color: batteryColor }}>
                {telemetry.battery}%
              </span>
            </div>
            <div className="status-bar">
              <span className="status-label">GPS Signal:</span>
              <div className="progress-bar">
                <div
                  className="progress-fill"
                  style={{
                    width: `${telemetry.gpsSignal}%`,
                    backgroundColor: signalColor
                  }}
                />
              </div>
              <span className="status-value" style={{ color: signalColor }}>
                {telemetry.gpsSignal}%
              </span>
            </div>
            {currentMission && (
              <div className="status-bar">
                <span className="status-label">Mission:</span>
                <div className="progress-bar">
                  <div
                    className="progress-fill mission-progress-fill"
                    style={{ width: `${missionProgress}%` }}
                  />
                </div>
                <span className="status-value">
                  {missionProgress}%
                </span>
              </div>
            )}
          </div>
        </div>

        {/* Position Data */}
        <div className="telemetry-section">
          <h4>Position</h4>
          <div className="data-grid">
            <div className="data-item">
              <span className="label">X:</span>
              <span className="value">{formatValue(telemetry.position?.x || 0)} m</span>
            </div>
            <div className="data-item">
              <span className="label">Y:</span>
              <span className="value">{formatValue(telemetry.position?.y || 0)} m</span>
            </div>
            <div className="data-item">
              <span className="label">Z:</span>
              <span className="value">{formatValue(telemetry.position?.z || 0)} m</span>
            </div>
          </div>
        </div>

        {/* Mission Info */}
        {currentMission && (
          <div className="telemetry-section">
            <h4>Current Mission</h4>
            <div className="mission-info">
              <div className="mission-name">{currentMission}</div>
              <div className="mission-progress">Progress: {missionProgress}%</div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// Mission Tab Component
const MissionTab = ({ flightController, onMissionStart, onMissionStop, flightState }) => {
  const [selectedMission, setSelectedMission] = useState(null);
  const [selectedType, setSelectedType] = useState('all');
  const [showManualControls, setShowManualControls] = useState(false);

  const missions = getAllMissions();
  const missionTypes = ['all', ...getMissionTypes()];

  const filteredMissions = selectedType === 'all'
    ? missions
    : missions.filter(mission => mission.type === selectedType);

  const handleMissionSelect = (mission) => {
    setSelectedMission(mission);
  };

  const handleStartMission = () => {
    if (selectedMission && onMissionStart) {
      onMissionStart(selectedMission);
    }
  };

  const handleStopMission = () => {
    if (onMissionStop) {
      onMissionStop();
    }
  };

  const handleTakeOff = () => {
    if (flightController) {
      flightController.takeOff();
    }
  };

  const handleLand = () => {
    if (flightController) {
      flightController.land();
    }
  };

  const handleEmergencyStop = () => {
    if (flightController) {
      flightController.emergencyStop();
    }
  };

  return (
    <div className="tab-content mission-tab">
      <div className="mission-content">

        {/* Control Tabs */}
        <div className="control-tabs">
          <button
            className={`tab ${!showManualControls ? 'active' : ''}`}
            onClick={() => setShowManualControls(false)}
          >
            🎯 Missions
          </button>
          <button
            className={`tab ${showManualControls ? 'active' : ''}`}
            onClick={() => setShowManualControls(true)}
          >
            🕹️ Manual
          </button>
        </div>

        {!showManualControls ? (
          <>
            {/* Mission Type Filter */}
            <div className="mission-section">
              <h3>Mission Type</h3>
              <select
                value={selectedType}
                onChange={(e) => setSelectedType(e.target.value)}
                className="mission-select"
              >
                {missionTypes.map(type => (
                  <option key={type} value={type}>
                    {type.charAt(0).toUpperCase() + type.slice(1)}
                  </option>
                ))}
              </select>
            </div>

            {/* Mission List */}
            <div className="mission-section">
              <h3>Available Missions</h3>
              <div className="mission-list">
                {filteredMissions.map(mission => (
                  <div
                    key={mission.id}
                    className={`mission-item ${selectedMission?.id === mission.id ? 'selected' : ''}`}
                    onClick={() => handleMissionSelect(mission)}
                  >
                    <div className="mission-header">
                      <h4>{mission.name}</h4>
                      <span className="mission-type">{mission.type}</span>
                    </div>
                    <div className="mission-details">
                      <p>{mission.description}</p>
                      <div className="mission-stats">
                        <span>Duration: {mission.duration}s</span>
                        <span>Waypoints: {mission.waypoints?.length || 0}</span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Mission Controls */}
            <div className="mission-section">
              <h3>Mission Controls</h3>
              <div className="mission-controls">
                <button
                  className="control-btn start"
                  onClick={handleStartMission}
                  disabled={!selectedMission || flightState?.autopilot}
                >
                  🚀 Start Mission
                </button>

                <button
                  className="control-btn stop"
                  onClick={handleStopMission}
                  disabled={!flightState?.autopilot}
                >
                  ⏹️ Stop Mission
                </button>
              </div>
            </div>
          </>
        ) : (
          <>
            {/* Manual Flight Controls */}
            <div className="mission-section">
              <h3>Flight Controls</h3>
              <div className="flight-controls">
                <button
                  className="control-btn takeoff"
                  onClick={handleTakeOff}
                  disabled={flightState?.isFlying}
                >
                  🛫 Take Off
                </button>

                <button
                  className="control-btn land"
                  onClick={handleLand}
                  disabled={!flightState?.isFlying}
                >
                  🛬 Land
                </button>

                <button
                  className="control-btn emergency"
                  onClick={handleEmergencyStop}
                >
                  🚨 Emergency Stop
                </button>
              </div>
            </div>

            {/* Flight Status */}
            <div className="mission-section">
              <h3>Flight Status</h3>
              <div className="status-display">
                <div className="status-item">
                  <span>Status:</span>
                  <span className={flightState?.isFlying ? 'flying' : 'grounded'}>
                    {flightState?.isFlying ? 'Flying' : 'Grounded'}
                  </span>
                </div>
                <div className="status-item">
                  <span>Mode:</span>
                  <span className={flightState?.autopilot ? 'auto' : 'manual'}>
                    {flightState?.autopilot ? 'Autopilot' : 'Manual'}
                  </span>
                </div>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  );
};

// Formation Tab Component
const FormationTab = ({ formationController, formationState }) => {
  const [selectedPattern, setSelectedPattern] = useState('circle');

  const patterns = [
    { id: 'circle', name: 'Circle Formation', description: 'Drones arranged in a circle' },
    { id: 'line', name: 'Line Formation', description: 'Drones in a straight line' },
    { id: 'triangle', name: 'Triangle Formation', description: 'Triangular formation' },
    { id: 'diamond', name: 'Diamond Formation', description: 'Diamond-shaped formation' },
    { id: 'v', name: 'V Formation', description: 'V-shaped formation' }
  ];

  const handlePatternChange = (patternId) => {
    setSelectedPattern(patternId);
    if (formationController) {
      // FormationController doesn't have setPattern, use available methods
      console.log(`Changing formation pattern to: ${patternId}`);
      // You could activate different programs based on pattern
      // formationController.activateProgram(patternId);
    }
  };

  const handleParameterChange = (param, value) => {
    if (formationController) {
      // Map parameter names to FormationController methods
      switch (param) {
        case 'spacing':
          // FormationController doesn't have setParameter, so we'll handle this differently
          console.log(`Setting formation ${param} to ${value}`);
          break;
        case 'speed':
          console.log(`Setting formation ${param} to ${value}`);
          break;
        case 'height':
          console.log(`Setting formation ${param} to ${value}`);
          break;
        default:
          console.log(`Unknown parameter: ${param}`);
      }
    }
  };

  return (
    <div className="tab-content formation-tab">
      <div className="formation-content">

        {/* Formation Patterns */}
        <div className="formation-section">
          <h3>Formation Patterns</h3>
          <div className="pattern-grid">
            {patterns.map(pattern => (
              <div
                key={pattern.id}
                className={`pattern-item ${selectedPattern === pattern.id ? 'selected' : ''}`}
                onClick={() => handlePatternChange(pattern.id)}
              >
                <div className="pattern-name">{pattern.name}</div>
                <div className="pattern-description">{pattern.description}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Formation Parameters */}
        <div className="formation-section">
          <h3>Parameters</h3>
          <div className="parameter-controls">
            <div className="parameter-item">
              <label>Spacing:</label>
              <input
                type="range"
                min="1"
                max="10"
                step="0.5"
                defaultValue={formationState?.spacing || 3}
                onChange={(e) => handleParameterChange('spacing', parseFloat(e.target.value))}
              />
              <span>{formationState?.spacing || 3}m</span>
            </div>
            <div className="parameter-item">
              <label>Speed:</label>
              <input
                type="range"
                min="0.5"
                max="5"
                step="0.1"
                defaultValue={formationState?.speed || 2}
                onChange={(e) => handleParameterChange('speed', parseFloat(e.target.value))}
              />
              <span>{formationState?.speed || 2}m/s</span>
            </div>
            <div className="parameter-item">
              <label>Height:</label>
              <input
                type="range"
                min="5"
                max="50"
                step="1"
                defaultValue={formationState?.height || 20}
                onChange={(e) => handleParameterChange('height', parseFloat(e.target.value))}
              />
              <span>{formationState?.height || 20}m</span>
            </div>
          </div>
        </div>

        {/* Formation Status */}
        <div className="formation-section">
          <h3>Formation Status</h3>
          <div className="status-grid">
            <div className="status-item">
              <div className="status-label">Active Drones</div>
              <div className="status-value">{formationState?.activeDrones || 0}</div>
            </div>
            <div className="status-item">
              <div className="status-label">Formation</div>
              <div className="status-value">{formationState?.currentPattern || 'None'}</div>
            </div>
            <div className="status-item">
              <div className="status-label">Sync Status</div>
              <div className="status-value">{formationState?.synchronized ? 'Synced' : 'Syncing'}</div>
            </div>
            <div className="status-item">
              <div className="status-label">Leader</div>
              <div className="status-value">{formationState?.leader || 'Main'}</div>
            </div>
          </div>
        </div>

        {/* Formation Controls */}
        <div className="formation-section">
          <h3>Controls</h3>
          <div className="formation-controls">
            <button
              className="control-btn start"
              onClick={() => formationController?.toggleFormation()}
              disabled={!formationController}
            >
              {formationState?.isFormationActive ? '⏹️ Stop Formation' : '🚀 Start Formation'}
            </button>
            <button
              className="control-btn stop"
              onClick={() => formationController?.activateProgram(null)}
              disabled={!formationController}
            >
              🔄 Reset Programs
            </button>
            <button
              className="control-btn reset"
              onClick={() => formationController?.initializeFormation(4)}
              disabled={!formationController}
            >
              🔄 Reset Formation
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

// Keyboard Tab Component
const KeyboardTab = ({ flightState }) => {
  const [activeKeys, setActiveKeys] = useState(new Set());

  // Simulate active keys for demonstration
  React.useEffect(() => {
    const handleKeyDown = (event) => {
      setActiveKeys(prev => new Set([...prev, event.code]));
    };

    const handleKeyUp = (event) => {
      setActiveKeys(prev => {
        const newSet = new Set(prev);
        newSet.delete(event.code);
        return newSet;
      });
    };

    window.addEventListener('keydown', handleKeyDown);
    window.addEventListener('keyup', handleKeyUp);

    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('keyup', handleKeyUp);
    };
  }, []);

  const isKeyActive = (keyCode) => activeKeys.has(keyCode);

  return (
    <div className="tab-content keyboard-tab">
      <div className="keyboard-content">

        {/* Control Status */}
        <div className="keyboard-section">
          <h3>Control Status</h3>
          <div className="status-indicators">
            <div className={`control-status ${!flightState?.autopilot ? 'enabled' : 'disabled'}`}>
              {!flightState?.autopilot ? '✅ ENABLED' : '🚫 DISABLED'}
            </div>
          </div>
        </div>

        {/* Movement Controls */}
        <div className="keyboard-section">
          <h3>Movement Controls</h3>
          <div className="key-grid movement-grid">
            <div className="key-row">
              <div className={`key-button ${isKeyActive('KeyW') || isKeyActive('ArrowUp') ? 'active' : ''}`}>
                <span className="key-label">W / ↑</span>
                <span className="key-action">Forward</span>
              </div>
            </div>
            <div className="key-row">
              <div className={`key-button ${isKeyActive('KeyA') || isKeyActive('ArrowLeft') ? 'active' : ''}`}>
                <span className="key-label">A / ←</span>
                <span className="key-action">Left</span>
              </div>
              <div className={`key-button ${isKeyActive('KeyS') || isKeyActive('ArrowDown') ? 'active' : ''}`}>
                <span className="key-label">S / ↓</span>
                <span className="key-action">Backward</span>
              </div>
              <div className={`key-button ${isKeyActive('KeyD') || isKeyActive('ArrowRight') ? 'active' : ''}`}>
                <span className="key-label">D / →</span>
                <span className="key-action">Right</span>
              </div>
            </div>
          </div>
        </div>

        {/* Altitude Controls */}
        <div className="keyboard-section">
          <h3>Altitude Controls</h3>
          <div className="key-grid altitude-grid">
            <div className={`key-button ${isKeyActive('Space') || isKeyActive('KeyR') ? 'active' : ''}`}>
              <span className="key-label">Space / R</span>
              <span className="key-action">Ascend</span>
            </div>
            <div className={`key-button ${isKeyActive('ShiftLeft') || isKeyActive('KeyF') ? 'active' : ''}`}>
              <span className="key-label">Shift / F</span>
              <span className="key-action">Descend</span>
            </div>
          </div>
        </div>

        {/* Rotation Controls */}
        <div className="keyboard-section">
          <h3>Rotation Controls</h3>
          <div className="key-grid rotation-grid">
            <div className={`key-button ${isKeyActive('KeyQ') ? 'active' : ''}`}>
              <span className="key-label">Q</span>
              <span className="key-action">Rotate Left</span>
            </div>
            <div className={`key-button ${isKeyActive('KeyE') ? 'active' : ''}`}>
              <span className="key-label">E</span>
              <span className="key-action">Rotate Right</span>
            </div>
          </div>
        </div>

        {/* Action Controls */}
        <div className="keyboard-section">
          <h3>Action Controls</h3>
          <div className="key-grid actions-grid">
            <div className={`key-button action-key ${isKeyActive('KeyT') ? 'active' : ''}`}>
              <span className="key-label">T</span>
              <span className="key-action">Take Off</span>
            </div>
            <div className={`key-button action-key ${isKeyActive('KeyL') ? 'active' : ''}`}>
              <span className="key-label">L</span>
              <span className="key-action">Land</span>
            </div>
            <div className={`key-button emergency-key ${isKeyActive('Escape') ? 'active' : ''}`}>
              <span className="key-label">ESC</span>
              <span className="key-action">Emergency Stop</span>
            </div>
          </div>
        </div>

        {/* Flight Status */}
        <div className="keyboard-section">
          <h3>Flight Status</h3>
          <div className="status-info">
            <div className="status-item">
              <span className="status-label">Flight Status:</span>
              <span className={`status-value ${flightState?.isFlying ? 'flying' : 'grounded'}`}>
                {flightState?.isFlying ? 'Flying' : 'Grounded'}
              </span>
            </div>
            <div className="status-item">
              <span className="status-label">Control Mode:</span>
              <span className={`status-value ${flightState?.autopilot ? 'auto' : 'manual'}`}>
                {flightState?.autopilot ? 'Autopilot' : 'Manual'}
              </span>
            </div>
          </div>
        </div>

        {/* Instructions */}
        <div className="keyboard-section">
          <h3>Instructions</h3>
          <div className="instructions">
            <p><strong>Movement:</strong> Use WASD or arrow keys to move the drone horizontally.</p>
            <p><strong>Altitude:</strong> Space/R to ascend, Shift/F to descend.</p>
            <p><strong>Rotation:</strong> Q/E to rotate left/right.</p>
            <p><strong>Actions:</strong> T to take off, L to land, ESC for emergency stop.</p>
            <p><strong>Note:</strong> Keyboard controls are disabled during autopilot mode.</p>
          </div>
        </div>
      </div>
    </div>
  );
};

// Environment Tab Component
const EnvironmentTab = ({
  showObstacles,
  setShowObstacles,
  showBoundaries,
  setShowBoundaries,
  showTerrain,
  setShowTerrain,
  mapSize,
  setMapSize
}) => {
  return (
    <div className="tab-content environment-tab">
      <div className="environment-content">

        {/* Map Settings */}
        <div className="environment-section">
          <h3>🗺️ Map Settings</h3>
          <div className="parameter-controls">
            <div className="parameter-item">
              <label>Map Size:</label>
              <input
                type="range"
                min="20"
                max="100"
                step="5"
                value={mapSize}
                onChange={(e) => setMapSize(parseInt(e.target.value))}
              />
              <span>{mapSize}m</span>
            </div>
          </div>
        </div>

        {/* Environment Features */}
        <div className="environment-section">
          <h3>🏗️ Environment Features</h3>
          <div className="feature-controls">
            <div className="feature-item">
              <label>
                <input
                  type="checkbox"
                  checked={showObstacles}
                  onChange={(e) => setShowObstacles(e.target.checked)}
                />
                <span className="feature-label">Buildings & Trees</span>
              </label>
              <p className="feature-description">
                Show buildings, trees, and other obstacles in the environment
              </p>
            </div>

            <div className="feature-item">
              <label>
                <input
                  type="checkbox"
                  checked={showBoundaries}
                  onChange={(e) => setShowBoundaries(e.target.checked)}
                />
                <span className="feature-label">Boundary Walls</span>
              </label>
              <p className="feature-description">
                Show perimeter walls that define the flight area boundaries
              </p>
            </div>

            <div className="feature-item">
              <label>
                <input
                  type="checkbox"
                  checked={showTerrain}
                  onChange={(e) => setShowTerrain(e.target.checked)}
                />
                <span className="feature-label">Terrain Features</span>
              </label>
              <p className="feature-description">
                Show hills, rocks, and natural terrain variations
              </p>
            </div>
          </div>
        </div>

        {/* Environment Info */}
        <div className="environment-section">
          <h3>ℹ️ Environment Info</h3>
          <div className="info-grid">
            <div className="info-item">
              <div className="info-label">Flight Area</div>
              <div className="info-value">{mapSize}m × {mapSize}m</div>
            </div>
            <div className="info-item">
              <div className="info-label">Max Altitude</div>
              <div className="info-value">50m</div>
            </div>
            <div className="info-item">
              <div className="info-label">Safety Zone</div>
              <div className="info-value">5m from boundaries</div>
            </div>
            <div className="info-item">
              <div className="info-label">Obstacles</div>
              <div className="info-value">{showObstacles ? 'Active' : 'Hidden'}</div>
            </div>
          </div>
        </div>

        {/* Environment Presets */}
        <div className="environment-section">
          <h3>🎨 Environment Presets</h3>
          <div className="preset-buttons">
            <button
              className="preset-btn urban"
              onClick={() => {
                setShowObstacles(true);
                setShowBoundaries(true);
                setShowTerrain(false);
                setMapSize(40);
              }}
            >
              🏙️ Urban
            </button>
            <button
              className="preset-btn natural"
              onClick={() => {
                setShowObstacles(true);
                setShowBoundaries(false);
                setShowTerrain(true);
                setMapSize(60);
              }}
            >
              🌲 Natural
            </button>
            <button
              className="preset-btn training"
              onClick={() => {
                setShowObstacles(false);
                setShowBoundaries(true);
                setShowTerrain(false);
                setMapSize(30);
              }}
            >
              🎯 Training
            </button>
            <button
              className="preset-btn mixed"
              onClick={() => {
                setShowObstacles(true);
                setShowBoundaries(true);
                setShowTerrain(true);
                setMapSize(50);
              }}
            >
              🌍 Mixed
            </button>
          </div>
        </div>

        {/* Safety Information */}
        <div className="environment-section safety-section">
          <h3>⚠️ Safety Information</h3>
          <div className="safety-info">
            <div className="safety-item">
              <span className="safety-icon">🚫</span>
              <span>Maintain 5m clearance from all obstacles</span>
            </div>
            <div className="safety-item">
              <span className="safety-icon">📏</span>
              <span>Respect boundary walls and no-fly zones</span>
            </div>
            <div className="safety-item">
              <span className="safety-icon">⬆️</span>
              <span>Maximum flight altitude: 50 meters</span>
            </div>
            <div className="safety-item">
              <span className="safety-icon">🔄</span>
              <span>Auto-return activated near boundaries</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// Camera Tab Component
const CameraTab = ({ cameraSettings, setCameraSettings }) => {
  const handleSettingChange = (setting, value) => {
    setCameraSettings(prev => ({
      ...prev,
      [setting]: value
    }));
  };

  return (
    <div className="tab-content camera-tab">
      <div className="camera-content">

        {/* Control Modes */}
        <div className="camera-section">
          <h3>🎮 Control Modes</h3>
          <div className="camera-controls">
            <div className="control-item">
              <label>
                <input
                  type="checkbox"
                  checked={cameraSettings.enableRotate}
                  onChange={(e) => handleSettingChange('enableRotate', e.target.checked)}
                />
                Enable Rotation
              </label>
            </div>
            <div className="control-item">
              <label>
                <input
                  type="checkbox"
                  checked={cameraSettings.enablePan}
                  onChange={(e) => handleSettingChange('enablePan', e.target.checked)}
                />
                Enable Panning (Right Click)
              </label>
            </div>
            <div className="control-item">
              <label>
                <input
                  type="checkbox"
                  checked={cameraSettings.enableZoom}
                  onChange={(e) => handleSettingChange('enableZoom', e.target.checked)}
                />
                Enable Zoom (Mouse Wheel)
              </label>
            </div>
            <div className="control-item">
              <label>
                <input
                  type="checkbox"
                  checked={cameraSettings.autoRotate}
                  onChange={(e) => handleSettingChange('autoRotate', e.target.checked)}
                />
                Auto Rotate
              </label>
            </div>
          </div>
        </div>

        {/* Sensitivity Settings */}
        <div className="camera-section">
          <h3>⚙️ Sensitivity</h3>
          <div className="parameter-controls">
            <div className="parameter-item">
              <label>Rotation Speed:</label>
              <input
                type="range"
                min="0.1"
                max="1.5"
                step="0.05"
                value={cameraSettings.rotateSpeed}
                onChange={(e) => handleSettingChange('rotateSpeed', parseFloat(e.target.value))}
              />
              <span>{cameraSettings.rotateSpeed.toFixed(2)}</span>
            </div>
            <div className="parameter-item">
              <label>Pan Speed:</label>
              <input
                type="range"
                min="0.1"
                max="1.5"
                step="0.05"
                value={cameraSettings.panSpeed}
                onChange={(e) => handleSettingChange('panSpeed', parseFloat(e.target.value))}
              />
              <span>{cameraSettings.panSpeed.toFixed(2)}</span>
            </div>
            <div className="parameter-item">
              <label>Zoom Speed:</label>
              <input
                type="range"
                min="0.2"
                max="2"
                step="0.1"
                value={cameraSettings.zoomSpeed}
                onChange={(e) => handleSettingChange('zoomSpeed', parseFloat(e.target.value))}
              />
              <span>{cameraSettings.zoomSpeed.toFixed(1)}</span>
            </div>
            <div className="parameter-item">
              <label>Smoothness:</label>
              <input
                type="range"
                min="0.01"
                max="0.2"
                step="0.005"
                value={cameraSettings.smoothness}
                onChange={(e) => handleSettingChange('smoothness', parseFloat(e.target.value))}
              />
              <span>{cameraSettings.smoothness.toFixed(3)}</span>
            </div>
            {cameraSettings.autoRotate && (
              <div className="parameter-item">
                <label>Auto Rotate Speed:</label>
                <input
                  type="range"
                  min="0.05"
                  max="1"
                  step="0.05"
                  value={cameraSettings.autoRotateSpeed}
                  onChange={(e) => handleSettingChange('autoRotateSpeed', parseFloat(e.target.value))}
                />
                <span>{cameraSettings.autoRotateSpeed.toFixed(2)}</span>
              </div>
            )}
          </div>
        </div>

        {/* Distance Limits */}
        <div className="camera-section">
          <h3>📏 Distance Limits</h3>
          <div className="parameter-controls">
            <div className="parameter-item">
              <label>Min Distance:</label>
              <input
                type="range"
                min="1"
                max="10"
                step="0.5"
                value={cameraSettings.minDistance}
                onChange={(e) => handleSettingChange('minDistance', parseFloat(e.target.value))}
              />
              <span>{cameraSettings.minDistance}m</span>
            </div>
            <div className="parameter-item">
              <label>Max Distance:</label>
              <input
                type="range"
                min="20"
                max="100"
                step="5"
                value={cameraSettings.maxDistance}
                onChange={(e) => handleSettingChange('maxDistance', parseFloat(e.target.value))}
              />
              <span>{cameraSettings.maxDistance}m</span>
            </div>
          </div>
        </div>

        {/* Camera Presets */}
        <div className="camera-section">
          <h3>🎨 Camera Presets</h3>
          <div className="preset-buttons">
            <button
              className="preset-btn follow"
              onClick={() => {
                setCameraSettings(prev => ({
                  ...prev,
                  target: [0, 2, 0],
                  rotateSpeed: 0.5,
                  panSpeed: 0.5,
                  zoomSpeed: 0.8,
                  smoothness: 0.08,
                  autoRotate: false
                }));
              }}
            >
              🎯 Follow Drone
            </button>
            <button
              className="preset-btn overview"
              onClick={() => {
                setCameraSettings(prev => ({
                  ...prev,
                  target: [0, 0, 0],
                  rotateSpeed: 0.3,
                  panSpeed: 0.3,
                  zoomSpeed: 0.6,
                  smoothness: 0.05,
                  autoRotate: false
                }));
              }}
            >
              🏞️ Overview
            </button>
            <button
              className="preset-btn cinematic"
              onClick={() => {
                setCameraSettings(prev => ({
                  ...prev,
                  autoRotate: true,
                  autoRotateSpeed: 0.2,
                  rotateSpeed: 0.3,
                  panSpeed: 0.2,
                  zoomSpeed: 0.5,
                  smoothness: 0.03
                }));
              }}
            >
              🔄 Cinematic
            </button>
            <button
              className="preset-btn responsive"
              onClick={() => {
                setCameraSettings(prev => ({
                  ...prev,
                  rotateSpeed: 0.8,
                  panSpeed: 0.8,
                  zoomSpeed: 1.2,
                  smoothness: 0.12,
                  autoRotate: false
                }));
              }}
            >
              ⚡ Responsive
            </button>
          </div>
        </div>

        {/* Control Instructions */}
        <div className="camera-section instructions-section">
          <h3>📖 Controls Guide</h3>
          <div className="instructions">
            <div className="instruction-item">
              <span className="instruction-icon">🖱️</span>
              <span><strong>Mouse Movement:</strong> Gentle free camera rotation (very smooth)</span>
            </div>
            <div className="instruction-item">
              <span className="instruction-icon">🖱️</span>
              <span><strong>Left Click + Drag:</strong> Controlled camera rotation with momentum</span>
            </div>
            <div className="instruction-item">
              <span className="instruction-icon">🖱️</span>
              <span><strong>Right Click + Drag:</strong> Pan camera position (distance-adaptive)</span>
            </div>
            <div className="instruction-item">
              <span className="instruction-icon">🎡</span>
              <span><strong>Mouse Wheel:</strong> Smooth zoom with configurable speed</span>
            </div>
            <div className="instruction-item">
              <span className="instruction-icon">🔄</span>
              <span><strong>Auto Rotate:</strong> Cinematic rotation for presentations</span>
            </div>
            <div className="instruction-item">
              <span className="instruction-icon">⚙️</span>
              <span><strong>Tip:</strong> Lower sensitivity = smoother, more precise control</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default UnifiedControlPanel;
